<template>
    <view class="container">
        <!-- 标签信息头部 -->
        <view class="tag-header" v-if="tag">
            <view class="tag-info">
                <text class="tag-name">{{ tag.name || '加载中...' }}</text>
                <text class="tag-count">{{ tag.count || 0 }} 篇文章</text>
            </view>
            <rich-text class="tag-desc" :nodes="tag.description" v-if="tag && tag.description"></rich-text>
        </view>

        <!-- 文章列表 - 网格布局 -->
        <view class="article-grid" v-if="articles.length">
            <view class="article-card" v-for="(article, index) in articles" :key="index" @tap="goToDetail(article)">
                <image class="card-image" :src="getPostImage(article)" mode="aspectFill" lazy-load />
                <view class="card-content">
                    <text class="card-title">{{ formatTitle(article.title.rendered) }}</text>
                    <view class="card-meta">
                        <text class="card-date">{{ formatDate(article.date) }}</text>
                        <view class="category-tags" v-if="article.categories && article.categories.length">
                            <text class="category-tag" v-for="(catId, idx) in article.categories" :key="idx"
                                v-if="getCategoryName(catId)">
                                {{ getCategoryName(catId) }}
                            </text>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-box" v-if="loading">
            <view class="loading">
                <view class="loading-spinner"></view>
                <text>加载中...</text>
            </view>
        </view>

        <!-- 没有更多 -->
        <view class="no-more" v-if="noMore && articles.length">
            <text>没有更多内容了</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && !articles.length">
            <text>该标签下暂无文章</text>
        </view>

        <!-- 返回顶部按钮 -->
        <view class="back-to-top" v-if="showBackToTop" @tap="backToTop">
            <uni-icons type="top" size="20" color="#fff"></uni-icons>
        </view>
    </view>
</template>

<script>
import api from '@/api/wordpress'

export default {
    data() {
        return {
            tagId: null,
            tag: null,
            taghref: '',
            articles: [],
            page: 1,
            loading: false,
            noMore: false,
            categories: {},
            showBackToTop: false,
            scrollTop: 0
        }
    },

    async onLoad(options) {
        if (options.id) {
            this.tagId = options.id;
            this.loading = true;
            try {
                await this.getTagDetail();
                if (this.taghref) {
                    await Promise.all([this.loadCategories(), this.getTagPosts()]);
                }
            } catch (e) {
                console.error('加载失败:', e);
                uni.showToast({ title: '加载失败', icon: 'none' });
            } finally {
                this.loading = false;
            }
        }
    },

    onPullDownRefresh() {
        this.refreshList();
    },

    onReachBottom() {
        if (!this.loading && !this.noMore) {
            this.page++;
            this.getTagPosts();
        }
    },

    // 添加页面滚动监听
    onPageScroll(e) {
        this.showBackToTop = e.scrollTop > 500;
        this.scrollTop = e.scrollTop;
    },

    methods: {
        async loadCategories() {
            try {
                const res = await api.getCategories();
                if (res.statusCode === 200 && res.data) {
                    const categoriesObj = {};
                    res.data.forEach(cat => categoriesObj[cat.id] = cat.name);
                    this.categories = categoriesObj;
                }
            } catch (e) {
                console.error('获取分类失败:', e);
            }
        },

        async getTagDetail() {
            try {
                const res = await api.getTagDetail(this.tagId);
                if (res.statusCode === 200) {
                    this.tag = res.data;
                    this.taghref = res.data._links['wp:post_type'][0].href;
                    uni.setNavigationBarTitle({ title: `#${res.data.name}` });
                }
            } catch (e) {
                console.error('获取标签详情失败:', e);
            }
        },

        async getTagPosts() {
            const res = await uni.request({
                url: this.taghref,
                data: { page: this.page, per_page: 10, _fields: 'id,title,excerpt,date,content,categories,modified' }
            });

            if (res.statusCode === 200) {
                const newArticles = res.data.map(article => ({
                    ...article,
                    imageUrl: api.getPostImage(article)
                }));

                if (this.page === 1) {
                    this.articles = newArticles;
                } else {
                    this.articles = [...this.articles, ...newArticles];
                }

                this.noMore = newArticles.length < 10;
            }
        },

        getPostImage(article) {
            return article.imageUrl || api.getPostImage(article);
        },

        formatTitle(title) {
            return title.replace(/&#8211;/g, '-').replace(/&amp;/g, '&').replace(/&#8220;/g, '"')
                .replace(/&#8221;/g, '"').replace(/&#8216;/g, "'").replace(/&#8217;/g, "'");
        },

        formatDate(date) {
            const d = new Date(date);
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        },

        getCategoryName(catId) {
            return this.categories[catId] || '';
        },

        // 修改刷新列表方法，添加动画效果
        async refreshList() {
            this.page = 1;
            this.noMore = false;
            this.articles = [];
            this.loading = true;

            // 显示刷新动画
            uni.showLoading({
                title: '刷新中...',
                mask: true
            });

            try {
                await Promise.all([
                    this.loadCategories(),
                    this.getTagDetail()
                ]);
                await this.getTagPosts();
            } catch (e) {
                console.error('刷新失败:', e);
                uni.showToast({
                    title: '刷新失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
                // 隐藏刷新动画
                uni.hideLoading();
                uni.stopPullDownRefresh();
            }
        },

        goToDetail(article) {
            uni.navigateTo({ url: `/pages/detail/detail?id=${article.id}&title=${encodeURIComponent(article.title.rendered)}` });
        },

        // 添加返回顶部方法
        backToTop() {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300
            });
        }
    }
}
</script>

<style>
.container {
    padding: 20rpx;
    min-height: 100vh;
    background-color: #f5f6fa;
}

/* 标签头部 */
.tag-header {
    background: linear-gradient(to right, #f0f4f8, #ffffff);
    padding: 40rpx 30rpx;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.tag-info {
    display: flex;
    align-items: baseline;
    gap: 16rpx;
    margin-bottom: 16rpx;
}

.tag-name {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
}

.tag-count {
    font-size: 26rpx;
    color: #999;
}

.tag-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
}

/* 网格布局 */
.article-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    padding: 10rpx;
}

.article-card {
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;
}

.article-card:active {
    transform: scale(0.98);
}

.card-image {
    width: 100%;
    height: 200rpx;
    object-fit: cover;
}

.card-content {
    padding: 20rpx;
}

.card-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
    margin-bottom: 16rpx;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.card-meta {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.card-date {
    font-size: 24rpx;
    color: #999;
}

.category-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8rpx;
}

.category-tag {
    font-size: 20rpx;
    color: #ff5722;
    background-color: rgba(255, 87, 34, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
}

/* 加载状态 */
.loading-box {
    padding: 40rpx 0;
    text-align: center;
}

.loading {
    display: inline-flex;
    align-items: center;
}

.loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #ff5722;
    border-radius: 50%;
    margin-right: 16rpx;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 空状态 */
.empty-state {
    padding: 100rpx 0;
    text-align: center;
    color: #999;
    font-size: 28rpx;
}

/* 返回顶部按钮 */
.back-to-top {
    position: fixed;
    right: 40rpx;
    bottom: 120rpx;
    width: 80rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #ff5722, #ff7043);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(255, 87, 34, 0.3);
    z-index: 999;
    transition: all 0.3s ease;
    animation: float 2s ease-in-out infinite;
}

.back-to-top:active {
    transform: scale(0.95);
    background: linear-gradient(135deg, #f4511e, #ff5722);
}

/* 添加悬浮动画 */
@keyframes float {
    0% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-6rpx);
    }

    100% {
        transform: translateY(0);
    }
}

/* 添加加载动画样式 */
.loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #ff5722;
    border-radius: 50%;
    margin-right: 16rpx;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 没有更多 */
.no-more {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 24rpx;
}</style>
